#!/usr/bin/python

import sys
import pexpect


def ssh_cmd(ip,username,passwd,cmd):
	ret = -1
	ssh = pexpect.spawn('ssh %s@%s "%s"' % (username,ip,cmd))
	try:
		i = ssh.expect(['password:','continue connecting (yes/no)?'],timeout=15)
		if i == 0:
			ssh.sendline(passwd)
		elif i == 1:
			ssh.sendline('yes\n')
			ssh.expect('password:')
			ssh.sendline(passwd)
		ssh.sendline(cmd)
		r = ssh.read()
		print r
		ret = 0
	except pexpect.EOF:
		print "EOF"
		ssh.close()
		ret = -1
	except pexpect.TIMEOUT:
		print "TIMEOUT"
		ssh.close()
		ret = 2
	return ret

def ShutDown(host):
	pass

if __name__ == "__main__":
	
	conf = open('./remoteshutdown.conf','r')
	for line in conf:
		if line.startswith("#"):
			continue
		host = line.split(',')
		print "============================================="
		print "Begin to connect %s..." % host[0]
		print "Run command..."
		ssh_cmd(host[0],host[1],host[2],host[3])
		print "== Execute finish! =="
	conf.close()	

	#ssh_cmd('10.43.2.171','1qaz2wsx','env')
	#if len(sys.argv) == 2 :
	#	print sys.argv[1]
